#include <stdio.h>
#include "driver/uart.h"
#include "sdkconfig.h"
#include "esp_log.h"

#include "wifi.h"

#define UART_TXD 23
#define UART_RXD 22
#define UART_RTS (UART_PIN_NO_CHANGE)
#define UART_CTS (UART_PIN_NO_CHANGE)

#define ECHO_UART_PORT_NUM      2
#define ECHO_UART_BAUD_RATE     115200
#define ECHO_TASK_STACK_SIZE    2048

#define BUF_SIZE (1024)

int uart_read(char* data, int len, int timeout)
{
    return uart_read_bytes(ECHO_UART_PORT_NUM, data, (len - 1), 20 / portTICK_RATE_MS);
}

int uart_write(const char* data, int len)
{
    return uart_write_bytes(ECHO_UART_PORT_NUM, data, len);
}

static void uart_task(void *pvParameters)
{
	int len;
	char *data = (char *) malloc(BUF_SIZE);

    while(1) {
		len = uart_read(data, (BUF_SIZE - 1), 20 / portTICK_RATE_MS);
		if (len > 0) {
			/* wifi tcp send to client */
			tcp_send(data, len);
		}
    }

	free(data);
}

void uart_init(void)
{
    /* Configure parameters of an UART driver,
     * communication pins and install the driver */
    uart_config_t uart_config = {
        .baud_rate = ECHO_UART_BAUD_RATE,
        .data_bits = UART_DATA_8_BITS,
        .parity    = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
        .source_clk = UART_SCLK_APB,
    };
    int intr_alloc_flags = 0;

#if CONFIG_UART_ISR_IN_IRAM
    intr_alloc_flags = ESP_INTR_FLAG_IRAM;
#endif

    ESP_ERROR_CHECK(uart_driver_install(ECHO_UART_PORT_NUM, 1024 * 2, 0, 0, NULL, intr_alloc_flags));
    ESP_ERROR_CHECK(uart_param_config(ECHO_UART_PORT_NUM, &uart_config));
    ESP_ERROR_CHECK(uart_set_pin(ECHO_UART_PORT_NUM, UART_TXD, UART_RXD, UART_RTS, UART_CTS));

	xTaskCreate(uart_task, "uart_task", 4096, NULL, 12, NULL);
}

